package likou.jindian;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/12/15 08:10
 */
public class _04_09 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> BSTSequences(TreeNode root) {
        if (root == null) {
            res.add(new ArrayList());
            return res;
        }
        ArrayDeque<TreeNode> level = new ArrayDeque<>();
        ArrayDeque<Integer> path = new ArrayDeque<>();

        level.add(root);
        dfs(level, path);
        return res;
    }

    private void dfs(ArrayDeque<TreeNode> level, ArrayDeque<Integer> path) {
        // base case
        if (level.isEmpty()) {
            res.add(new ArrayList(path));
        }

        int n = level.size();
        for (int i=0; i<n; ++i) {
            TreeNode cur = level.poll();
            path.add(cur.val);
            if (cur.left != null) level.add(cur.left);
            if (cur.right != null) level.add(cur.right);

            dfs(level, path);

            if (cur.right != null) level.pollLast();
            if (cur.left != null) level.pollLast();
            path.pollLast(); // 要从 path 的尾部 remove, 因为回溯前是 add 到 path 的队尾的
            level.add(cur);
        }
    }
}
